import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/common/account_avatar_widget.dart';
import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/profile/account_profile_setting/account_profile_setting_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

// 个人资料设置页面
class AccountProfileSettingPage extends StatefulWidget {
  const AccountProfileSettingPage({super.key});

  @override
  State<AccountProfileSettingPage> createState() =>
      _AccountProfileSettingPageState();
}

// 个人资料设置页面
class _AccountProfileSettingPageState extends State<AccountProfileSettingPage> {
  @override
  void initState() {
    super.initState();
    context.read<AccountProfileSettingPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text(AppStrings.profileTitle)),
      body: _buildMainBody(context),
    );
  }

  // 根据用户资料状态展示不同内容
  Widget _buildMainBody(BuildContext context) {
    return Selector<AccountProfileSettingPageLogic, bool>(
      selector: (context, logic) => logic.isProfileEmpty,
      builder: (context, isProfileEmpty, child) {
        if (isProfileEmpty) {
          return Selector<AccountProfileSettingPageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) =>
                Tuple2(logic.isLoading, logic.isError),
            builder: (context, item, child) {
              return EmptyContentWidget(
                isLoading: item.item1,
                isError: item.item2,
                // 重新加载操作
                reloadAction: () {
                  context
                      .read<AccountProfileSettingPageLogic>()
                      .loadUserProfile();
                },
              );
            },
          );
        } else {
          return _buildMainListView(context);
        }
      },
    );
  }

  // 构建个人资料列表
  Widget _buildMainListView(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.surface,
      child: ScrollConfiguration(
        behavior: const ScrollBehavior().copyWith(scrollbars: false),
        child: ListView(
          children: [
            const SizedBox(height: 15),
            // 头像
            _buildAvatarSelectCell(context),
            // 昵称
            _buildInfoTextCell(
              context: context,
              title: AppStrings.nickname,
              onTap: () {
                context.pushNamed(AppRouter.kNicknameSetting);
              },
              selector: (logic) => logic.nickname,
            ),
            // 职业
            _buildInfoTextCell(
              context: context,
              title: AppStrings.profession,
              onTap: () {
                context.pushNamed(AppRouter.kProfessionSetting);
              },
              selector: (logic) => logic.profession,
            ),
            // 性别
            _buildInfoTextCell(
              context: context,
              title: AppStrings.gender,
              onTap: () {
                _selectorGender(context);
              },
              selector: (logic) {
                switch (logic.gender) {
                  case 'm':
                    return AppStrings.male;
                  case 'f':
                    return AppStrings.female;
                  default:
                    return AppStrings.genderUnknown;
                }
              },
            ),
            // 地区
            _buildInfoTextCell(
              context: context,
              title: AppStrings.region,
              onTap: () {
                context.pushNamed(
                  AppRouter.kLocationSetting,
                  queryParameters: {'level': '1'},
                );
              },
              selector: (logic) => logic.location,
            ),
            // 签名
            _buildInfoTextCell(
              context: context,
              title: AppStrings.introduction,
              onTap: () {
                context.pushNamed(AppRouter.kIntroductionSetting);
              },
              selector: (logic) => logic.introduction,
            ),
            // 账号与安全
            const SizedBox(height: 30),
            _buildInfoTextCell(
              context: context,
              title: AppStrings.accountSecurity,
              onTap: () {
                context.pushNamed(AppRouter.kSecuritySetting);
              },
              selector: (logic) => AppStrings.accountSecurityTip,
            ),
          ],
        ),
      ),
    );
  }

  // 构建用户头像
  Widget _buildAvatarSelectCell(BuildContext context) {
    return InkWell(
      onTap: () {
        final logic = context.read<AccountProfileSettingPageLogic>();
        logic.updateUserAvatar();
      },
      child: Container(
        height: 60,
        padding: const EdgeInsets.symmetric(horizontal: 20),
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Row(
          children: [
            Text(
              AppStrings.avatar,
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const Spacer(),
            ClipRRect(
              borderRadius: BorderRadius.circular(22),
              child: Container(
                width: 44,
                height: 44,
                color: Theme.of(context).colorScheme.surface,
                child: const AccountAvatarWidget(),
              ),
            ),
            const SizedBox(width: 5),
            const Icon(Icons.arrow_forward_ios, size: 15, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  // 构建信息文本
  Widget _buildInfoTextCell({
    required BuildContext context,
    required String title,
    required GestureTapCallback onTap,
    required String? Function(AccountProfileSettingPageLogic logic) selector,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 60,
        padding: const EdgeInsets.symmetric(horizontal: 20),
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Row(
          children: [
            Text(title, style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(width: 10),
            Expanded(
              child: Selector<AccountProfileSettingPageLogic, String?>(
                selector: (context, logic) => selector(logic),
                builder: (context, v, child) {
                  final style = Theme.of(
                    context,
                  ).textTheme.bodyMedium?.copyWith(color: Colors.grey);
                  return Text(
                    v ?? '',
                    style: style,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    textAlign: TextAlign.right,
                  );
                },
              ),
            ),
            const SizedBox(width: 5),
            const Icon(Icons.arrow_forward_ios, size: 15, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  // 修改性别
  void _selectorGender(BuildContext context) {
    final logic = context.read<AccountProfileSettingPageLogic>();
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return _GenderSelector(
          gender: logic.gender,
          onGender: logic.updateGender,
        );
      },
    );
  }
}

// 修改性别
class _GenderSelector extends StatefulWidget {
  final String? gender;
  final Function(String) onGender;
  const _GenderSelector({required this.gender, required this.onGender});

  @override
  State<_GenderSelector> createState() => __GenderSelectorState();
}

class __GenderSelectorState extends State<_GenderSelector> {
  String? _gender;

  @override
  void initState() {
    super.initState();
    _gender = widget.gender;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 20),
          ListTile(
            leading: const Icon(Icons.male, size: 20),
            title: Text(AppStrings.male),
            trailing: _gender == 'm' ? const Icon(Icons.check, size: 22) : null,
            onTap: () {
              setState(() {
                _gender = 'm';
              });
              widget.onGender('m');
              Navigator.of(context).pop();
            },
          ),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Divider(height: 0.25),
          ),
          ListTile(
            leading: const Icon(Icons.female, size: 20),
            title: Text(AppStrings.female),
            trailing: _gender == 'f' ? const Icon(Icons.check, size: 22) : null,
            onTap: () {
              setState(() {
                _gender = 'f';
              });
              widget.onGender('f');
              Navigator.of(context).pop();
            },
          ),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Divider(height: 0.25),
          ),
        ],
      ),
    );
  }
}
